package com.hd.system.common.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import com.hd.system.common.model.DocumentModel;
import com.hd.system.common.model.ImageModel;
import com.hd.util.RandomUtils;


@Service("fileUploadService")
public class FileUploadService {
	private String tempPath = "/uploadImageTemp"; // 临时存储目录

	private String savePath = "/upload/image";// 存储目录

	final long MAX_SIZE = 10 * 1024 * 1024;
	final int THRE_SHOLD_SIZE = 4096;

	@Autowired
	private DocumentService documentService;

	@Autowired
	private ImageService imageService;


	public void uploadFileImage(HttpServletRequest request) throws Exception {
		try {

			// 获取临时目录
			String tempPathDir = request.getSession().getServletContext().getRealPath(this.tempPath);
			File tempPathDirFile = new File(tempPathDir);
			if (!tempPathDirFile.exists()) {
				tempPathDirFile.mkdirs();
			}

			// 存储目录
			String realDir = request.getSession().getServletContext().getRealPath(this.savePath);
			File saveFilePath = new File(realDir);
			if (!saveFilePath.exists()) {
				saveFilePath.mkdirs();
			}
			realDir = realDir.replace("\\", "/");

			String image = request.getParameter("image");
			// 只允许image
			String header = "data:image";
			String[] imageArr = image.split(",");
			if (imageArr[0].contains(header)) {// 是img的
				// 去掉头部
				image = imageArr[1];
				// image = image.substring(header.length());
				// 写入磁盘
				try {
					byte[] decodedBytes = Base64.getDecoder().decode(image); // 将字符串格式的image转为二进制流（biye[])的decodedBytes
					String photoName = RandomUtils.getRandomString(8) + ".jpg";
					String imgFilePath = realDir + "/" + photoName; // 指定图片要存放的位置

					FileOutputStream out = new FileOutputStream(imgFilePath); // 新建一个文件输出器，并为它指定输出位置imgFilePath
					out.write(decodedBytes); // 利用文件输出器将二进制格式decodedBytes输出
					out.close(); // 关闭文件输出器

					// 图片保存
					ImageModel fileUpload = new ImageModel();
					imageService.save(fileUpload);

					System.out.println("图片上传成功！");
				} catch (Exception e) {
					throw new Exception(e.getMessage());
				}
			}
		} catch (Exception et) {
			throw new Exception(et.getMessage());
		}
	}
	
	public void uploadFile(HttpServletRequest request) throws Exception {
		try {

			// 获取临时目录
			String tempPathDir = request.getSession().getServletContext().getRealPath(this.tempPath);
			File tempPathDirFile = new File(tempPathDir);
			if (!tempPathDirFile.exists()) {
				tempPathDirFile.mkdirs();
			}

			// 存储目录
			String realDir = request.getSession().getServletContext().getRealPath(this.savePath);
			File saveFilePath = new File(realDir);
			if (!saveFilePath.exists()) {
				saveFilePath.mkdirs();
			}
			realDir = realDir.replace("\\", "/");

			String image = request.getParameter("image");
			// 只允许image
			String header = "data:image";
			String[] imageArr = image.split(",");
			if (imageArr[0].contains(header)) {// 是img的
				// 去掉头部
				image = imageArr[1];
				// image = image.substring(header.length());
				// 写入磁盘
				try {
					byte[] decodedBytes = Base64.getDecoder().decode(image); // 将字符串格式的image转为二进制流（biye[])的decodedBytes
					String photoName = RandomUtils.getRandomString(8) + ".jpg";
					String imgFilePath = realDir + "/" + photoName; // 指定图片要存放的位置

					FileOutputStream out = new FileOutputStream(imgFilePath); // 新建一个文件输出器，并为它指定输出位置imgFilePath
					out.write(decodedBytes); // 利用文件输出器将二进制格式decodedBytes输出
					out.close(); // 关闭文件输出器

					// 文件保存
					DocumentModel model = new DocumentModel();
					documentService.save(model);

					System.out.println("文件上传成功！");
				} catch (Exception e) {
					throw new Exception(e.getMessage());
				}
			}
		} catch (Exception et) {
			throw new Exception(et.getMessage());
		}
	}

	public String base64StringToImage(String fileId) throws Exception {
		// 获取图片

		String filePath = "";
			byte[] imageByte = this.image2byte(filePath);
			return Base64Utils.encodeToString(imageByte);
	}

	public byte[] image2byte(String path) {
		byte[] data = null;
		FileImageInputStream input = null;
		try {
			input = new FileImageInputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int numBytesRead = 0;
			while ((numBytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, numBytesRead);
			}
			data = output.toByteArray();
			output.close();
			input.close();
		} catch (FileNotFoundException ex1) {
			ex1.printStackTrace();
		} catch (IOException ex1) {
			ex1.printStackTrace();
		}
		return data;
	}
}
